//
//  filterTools.swift
//  uiKit-demo
//
//  Created by 陈澎 on 2025/1/8.
//

import UIKit

struct FilterItem {
    var title: String
    var positionX: CGFloat
    var selected: Bool?
}
class FilterToolsView: UIViewController {
    let filterArr: [FilterItem] = [
        FilterItem(title: "综合", positionX: 33, selected: true),
        FilterItem(title: "销售", positionX: 127),
        FilterItem(title: "价格", positionX: 214),
        FilterItem(title: "筛选", positionX: 306)
    ]
    var tabLabels: [UILabel] = []
    
    @objc func chosedTab(_ sender: UITapGestureRecognizer) {
        print("点击")
        guard let selectedLabel = sender.view as? UILabel else {return}
        for label in tabLabels {
            if label == selectedLabel {
                label.textColor = label.textColor == .red ? .black : .red
            } else {
                label.textColor = .black
            }
        }
    }
    func createTabItem(item: FilterItem) -> UILabel {
        let label = UILabel()
        label.text = item.title
        label.textColor =  item.selected == true ? .red : .black
        label.font = UIFont.systemFont(ofSize: 14)
        label.frame = CGRect(x: item.positionX, y: 0, width: 50, height: 39)
        // 启用用户交互
        label.isUserInteractionEnabled = true
       
        return label
    }
    // 自定义初始化器
    func render(parentView: UIView) {
          let filterView = UIView()
          filterView.layer.cornerRadius = 10
          filterView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
          // 在这里进行初始化工作
          for (_, val) in filterArr.enumerated() {
              let curLabel = createTabItem(item: val)
              let tapGesture = UITapGestureRecognizer(target: self, action: #selector(chosedTab(_:)))
              curLabel.addGestureRecognizer(tapGesture)
              tabLabels.append(curLabel)
              filterView.addSubview(curLabel)
          }
        filterView.translatesAutoresizingMaskIntoConstraints = false
        filterView.backgroundColor = .white
        parentView.addSubview(filterView)
        NSLayoutConstraint.activate([
            filterView.topAnchor.constraint(equalTo: parentView.safeAreaLayoutGuide.topAnchor),
            filterView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor),
            filterView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor),
            filterView.heightAnchor.constraint(equalToConstant: 39)
        ])
      }
}
